<template>
  <div class="feedback-manage">
    <TopBar />

    <div class="content">
      <MenuLine />

      <div class="operation-bar">
        <el-button type="primary" @click="openAddDialog" :icon="Plus">添加反馈</el-button>
      </div>

      <el-table :data="feedbackList" style="width: 100%" border v-loading="feedbackStore.loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content" label="反馈内容" show-overflow-tooltip />
        <el-table-column prop="submitterName" label="提交人" width="150" />
        <el-table-column prop="createTime" label="提交时间" width="180" />
        <el-table-column prop="reply" label="回复内容" show-overflow-tooltip>
           <template #default="{ row }">
             <span v-if="row.reply">{{ row.reply }}</span>
             <el-tag v-else type="info" size="small">未回复</el-tag>
           </template>
        </el-table-column>
        <el-table-column prop="replierName" label="回复人" width="150">
           <template #default="{ row }">
             {{ row.replierName || '-' }}
           </template>
        </el-table-column>
        <el-table-column prop="replyTime" label="回复时间" width="180">
           <template #default="{ row }">
             {{ row.replyTime || '-' }}
           </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button
              type="success"
              size="small"
              @click="openReplyDialog(row)"
              :icon="EditPen"
            >
              {{ row.reply ? '编辑' : '回复' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteFeedback(row.id)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        title="添加反馈"
        v-model="addDialogVisible"
        width="40%"
        @close="resetAddForm"
      >
        <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="80px">
          <el-form-item label="内容" prop="content">
            <el-input
              v-model="addForm.content"
              type="textarea"
              :rows="5"
              placeholder="请输入反馈内容"
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </template>
      </el-dialog>

      <el-dialog
        :title="replyDialogTitle"
        v-model="replyDialogVisible"
        width="40%"
        @close="resetReplyForm"
      >
         <el-descriptions :column="1" border>
            <el-descriptions-item label="反馈内容">{{ currentFeedback?.content }}</el-descriptions-item>
            <el-descriptions-item label="提交人">{{ currentFeedback?.submitterName }}</el-descriptions-item>
            <el-descriptions-item label="提交时间">{{ currentFeedback?.createTime }}</el-descriptions-item>
         </el-descriptions>
         <el-divider />
        <el-form :model="replyForm" :rules="replyRules" ref="replyFormRef" label-width="80px" style="margin-top: 20px;">
          <el-form-item label="回复" prop="reply">
            <el-input
              v-model="replyForm.reply"
              type="textarea"
              :rows="5"
              placeholder="请输入回复内容"
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReplyForm">确定</el-button>
        </template>
      </el-dialog>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { Plus, EditPen, Delete } from '@element-plus/icons-vue';
import { useFeedbackStore, type Feedback, type FeedbackCreatePayload, type FeedbackReplyPayload } from '@/stores/feedback';
import { useUserStore } from '@/stores/user'; // To get current user ID
import TopBar from '@/components/TopBar.vue';
import MenuLine from '@/components/MenuLine.vue';

// Stores
const feedbackStore = useFeedbackStore();
const userStore = useUserStore();

// State
const feedbackList = ref<Feedback[]>([]);
const addDialogVisible = ref(false);
const replyDialogVisible = ref(false);
const currentFeedback = ref<Feedback | null>(null); // For reply dialog context

// Forms & Refs
const addForm = ref<FeedbackCreatePayload>({ content: '', submitterId: 0 });
const replyForm = ref<FeedbackReplyPayload>({ id: 0, reply: '', replierId: 0 });
const addFormRef = ref<FormInstance>();
const replyFormRef = ref<FormInstance>();

// Computed properties
const replyDialogTitle = computed(() => currentFeedback.value?.reply ? '编辑回复' : '添加回复');
const loggedInUserId = computed(() => userStore.user?.id); // Get logged-in user ID

// Validation Rules
const addRules: FormRules = {
  content: [
    { required: true, message: '反馈内容不能为空', trigger: 'blur' },
    { min: 1, max: 1000, message: '内容长度为 1-1000 字符', trigger: 'blur' },
  ],
};
const replyRules: FormRules = {
  reply: [
    { required: true, message: '回复内容不能为空', trigger: 'blur' },
    { min: 1, max: 1000, message: '回复长度为 1-1000 字符', trigger: 'blur' },
  ],
};

// Methods
const fetchFeedbacks = async () => {
  try {
    await feedbackStore.fetchFeedbacks();
    feedbackList.value = feedbackStore.feedbacks;
  } catch (error: any) {
    ElMessage.error(error.message || '获取反馈列表失败');
  }
};

const openAddDialog = () => {
  if (!loggedInUserId.value) {
    ElMessage.error('请先登录后再提交反馈');
    // Optionally redirect to login: router.push('/login');
    return;
  }
  resetAddForm();
  addForm.value.submitterId = loggedInUserId.value;
  addDialogVisible.value = true;
};

const openReplyDialog = (row: Feedback) => {
  if (!loggedInUserId.value) {
    ElMessage.error('请先登录后再进行回复');
    return;
  }
  currentFeedback.value = row;
  replyForm.value = {
    id: row.id,
    reply: row.reply || '', // Pre-fill if editing
    replierId: loggedInUserId.value,
  };
  replyDialogVisible.value = true;
};

const submitAddForm = async () => {
  if (!addFormRef.value) return;
  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await feedbackStore.createFeedback(addForm.value);
        ElMessage.success('反馈添加成功');
        addDialogVisible.value = false;
        await fetchFeedbacks(); // Refresh list
      } catch (error: any) {
        ElMessage.error(error.message || '添加反馈失败');
      }
    }
  });
};

const submitReplyForm = async () => {
  if (!replyFormRef.value || !currentFeedback.value) return;
  await replyFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await feedbackStore.replyToFeedback(replyForm.value);
        ElMessage.success('回复成功');
        replyDialogVisible.value = false;
        await fetchFeedbacks(); // Refresh list
      } catch (error: any) {
        ElMessage.error(error.message || '回复失败');
      }
    }
  });
};

const handleDeleteFeedback = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定删除此反馈记录吗？此操作不可撤销。', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await feedbackStore.deleteFeedback(id);
    ElMessage.success('反馈删除成功');
    await fetchFeedbacks(); // Refresh list
  } catch (error: any) {
    if (error !== 'cancel') { // Ignore cancel action
      ElMessage.error(error.message || '删除反馈失败');
    } else {
      ElMessage.info('取消删除');
    }
  }
};

const resetAddForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  addForm.value = { content: '', submitterId: loggedInUserId.value || 0 };
};

const resetReplyForm = () => {
  if (replyFormRef.value) {
    replyFormRef.value.resetFields();
  }
  replyForm.value = { id: 0, reply: '', replierId: loggedInUserId.value || 0 };
  currentFeedback.value = null;
};

// Lifecycle Hook
onMounted(() => {
  fetchFeedbacks();
});
</script>

<style scoped>
.feedback-manage {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding-top: 60px;
  width: 80%;
  margin: 0 auto;
  padding-bottom: 60px;
}

.operation-bar {
  margin: 20px 0;
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-tag {
  cursor: default;
}

/* Add some spacing in dialogs */
.el-form {
  padding: 10px 0;
}
.el-divider {
    margin: 15px 0;
}
</style>